package com.ruicar.afs.cloud.afscase.infomanagement.service.impl;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruicar.afs.cloud.afscase.infomanagement.condition.CaseInfoQueryCondition;
import com.ruicar.afs.cloud.afscase.infomanagement.entity.CaseBaseInfo;
import com.ruicar.afs.cloud.afscase.infomanagement.entity.CaseCostInfoOriginal;
import com.ruicar.afs.cloud.afscase.infomanagement.mapper.CaseCostInfoMapper;
import com.ruicar.afs.cloud.afscase.infomanagement.service.*;
import com.ruicar.afs.cloud.afscase.infomanagement.vo.ApproveCostPageInfoVo;
import com.ruicar.afs.cloud.afscase.infomanagement.vo.FinCostInfoVo;
import com.ruicar.afs.cloud.afscase.loanapprove.vo.CaseCostInfoVO;
import com.ruicar.afs.cloud.bizcommon.business.entity.FinCostDetails;
import com.ruicar.afs.cloud.bizcommon.business.entity.FinDiscountDetails;
import com.ruicar.afs.cloud.bizcommon.business.entity.FinFinancingItems;
import com.ruicar.afs.cloud.common.modules.afscorebusiness.enums.CostTypeEnum;
import com.ruicar.afs.cloud.common.modules.afscorebusiness.enums.FinanceItemEnum;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>Description: </p>
 *
 * @author ZC.GUO
 * @version 1.0
 * @date create on 2020-05-13 15:20
 */
@Service
@AllArgsConstructor
@Data
@Slf4j
public class CaseCostInfoServiceImpl extends ServiceImpl<CaseCostInfoMapper, FinCostDetails> implements CaseCostInfoService {


    private CaseBaseInfoService caseBaseInfoService;

    private CaseDiscountDetailService caseDiscountDetailService;

    private CaseFinancingItemsService caseFinancingItemsService;

    private CaseCostInfoOriginalService caseCostInfoOriginalService;

    @Override
    public ApproveCostPageInfoVo queryApproveCostPageInfo(CaseInfoQueryCondition caseInfoQueryCondition) {

        ApproveCostPageInfoVo approveCostPageInfoVo = new ApproveCostPageInfoVo();

        /**  产品信息  **/
        CaseBaseInfo caseBaseInfo = caseBaseInfoService.getOne(Wrappers.<CaseBaseInfo>query().lambda()
                .eq(CaseBaseInfo::getApplyNo, caseInfoQueryCondition.getApplyNo()));
        approveCostPageInfoVo.setProductName(caseBaseInfo.getProductName());
        approveCostPageInfoVo.setProductId(caseBaseInfo.getProductId());

        boolean sameProduct = false;
        /**  车款融资信息  **/
        FinCostDetails carAmtCostInfo = this.getOne(Wrappers.<FinCostDetails>query().lambda()
                .eq(FinCostDetails::getApplyNo, caseInfoQueryCondition.getApplyNo())
                .eq(FinCostDetails::getCostType, CostTypeEnum.CARAMT.getCode())
                .eq(StringUtils.isNotEmpty(caseInfoQueryCondition.getCarId()), FinCostDetails::getCarId, caseInfoQueryCondition.getCarId()));

        approveCostPageInfoVo = this.setCarAmt(approveCostPageInfoVo, carAmtCostInfo);
        /**  附加贷融资信息  **/
        FinCostDetails affix = this.getOne(Wrappers.<FinCostDetails>query().lambda()
                .eq(FinCostDetails::getApplyNo, caseInfoQueryCondition.getApplyNo())
                .eq(FinCostDetails::getCostType, CostTypeEnum.AFFIXAMT.getCode())
                .eq(StringUtils.isNotEmpty(caseInfoQueryCondition.getCarId()), FinCostDetails::getCarId, caseInfoQueryCondition.getCarId()));

        approveCostPageInfoVo = this.setAffix(approveCostPageInfoVo, affix);

        /**  是否同一产品  **/
        if (ObjectUtils.isNotEmpty(affix)) {
            if (carAmtCostInfo.getProductId().equals(affix.getProductId())) {
                sameProduct = true;
            }
        }
        approveCostPageInfoVo.setSameProduct(sameProduct);

        return approveCostPageInfoVo;
    }


    /**
     * <p>Description: 设置车款融资信息</p>
     *
     * @param
     * @return
     */
    private ApproveCostPageInfoVo setCarAmt(ApproveCostPageInfoVo approveCostPageInfoVo, FinCostDetails carAmtCostInfo) {
        /**  车款融资信息  **/
        FinCostInfoVo carAmtInfo = new FinCostInfoVo();

        /**  车款原始融资信息初始化  **/
        approveCostPageInfoVo.setCarAmtCopy(new CaseCostInfoOriginal());

        carAmtInfo.setSubsidyDetail(new ArrayList<FinDiscountDetails>());
        if (ObjectUtils.isNotEmpty(carAmtCostInfo)) {
            /**  设置车款融资信息  **/
            BeanUtils.copyProperties(carAmtCostInfo, carAmtInfo);
            /**  设置贴息明细  **/
            List<FinDiscountDetails> subsidyDetail = caseDiscountDetailService.list(Wrappers.<FinDiscountDetails>query().lambda()
                    .eq(FinDiscountDetails::getCostId, carAmtCostInfo.getId())
            );
            if (!CollectionUtils.isEmpty(subsidyDetail)) {
                carAmtInfo.setSubsidyDetail(subsidyDetail);
            }
            /**还款方式*/
            approveCostPageInfoVo.setRepayMode(carAmtCostInfo.getAlgorithmType());

            /**  设置总金额  **/
            approveCostPageInfoVo.setContAmt(ObjectUtils.isNotEmpty(approveCostPageInfoVo.getContAmt()) ? approveCostPageInfoVo.getContAmt().add(carAmtCostInfo.getContractAmt()) : carAmtCostInfo.getContractAmt());
            approveCostPageInfoVo.setLoanAmt(ObjectUtils.isNotEmpty(approveCostPageInfoVo.getLoanAmt()) ? approveCostPageInfoVo.getLoanAmt().add(carAmtCostInfo.getLoanAmt()) : carAmtCostInfo.getLoanAmt());
            approveCostPageInfoVo.setDownPayAmt(ObjectUtils.isNotEmpty(approveCostPageInfoVo.getDownPayAmt()) ? approveCostPageInfoVo.getDownPayAmt().add(carAmtCostInfo.getDownPayAmt()) : carAmtCostInfo.getDownPayAmt());
            approveCostPageInfoVo.setTailPayAmt(ObjectUtils.isNotEmpty(approveCostPageInfoVo.getTailPayAmt()) ? approveCostPageInfoVo.getTailPayAmt().add(carAmtCostInfo.getTailPayAmt()) : carAmtCostInfo.getTailPayAmt());
            approveCostPageInfoVo.setMonthPayAmt(ObjectUtils.isNotEmpty(approveCostPageInfoVo.getMonthPayAmt()) ? approveCostPageInfoVo.getMonthPayAmt().add(carAmtCostInfo.getMonthPayAmt()) : carAmtCostInfo.getMonthPayAmt());
            approveCostPageInfoVo.setInterestAmt(ObjectUtils.isNotEmpty(approveCostPageInfoVo.getInterestAmt()) ? approveCostPageInfoVo.getInterestAmt().add(carAmtCostInfo.getTotalInterest()) : carAmtCostInfo.getTotalInterest());

        }
        approveCostPageInfoVo.setCarAmt(carAmtInfo);


        return approveCostPageInfoVo;
    }

    /**
     * <p>Description: 设置附加贷融资信息</p>
     *
     * @param
     * @return
     */
    private ApproveCostPageInfoVo setAffix(ApproveCostPageInfoVo approveCostPageInfoVo, FinCostDetails affix) {
        FinCostInfoVo affixInfo = new FinCostInfoVo();
        /**  设置附加贷标记  **/
        approveCostPageInfoVo.setHasAffix(false);
        /**  附加贷原始融资信息初始化  **/
        approveCostPageInfoVo.setAffixCopy(new CaseCostInfoOriginal());
        affixInfo.setSubsidyDetail(new ArrayList<FinDiscountDetails>());
        affixInfo.setFinancingItems(new ArrayList<FinFinancingItems>());
        if (ObjectUtils.isNotEmpty(affix)) {
            /**  设置附加贷融资信息  **/
            BeanUtils.copyProperties(affix, affixInfo);

            /**  附加贷原始融资信息  **/
            CaseCostInfoOriginal affixCopy = caseCostInfoOriginalService.getById(affix.getId());
            approveCostPageInfoVo.setAffixCopy(ObjectUtils.isNotEmpty(affixCopy) ? affixCopy : new CaseCostInfoOriginal());


            /**  设置贴息明细  **/
            List<FinDiscountDetails> subsidyDetail = caseDiscountDetailService.list(Wrappers.<FinDiscountDetails>query().lambda()
                    .eq(FinDiscountDetails::getCostId, affix.getId())
            );
            if (!CollectionUtils.isEmpty(subsidyDetail)) {
                affixInfo.setSubsidyDetail(subsidyDetail);
            }
            /**  设置附加贷明细  **/
            List<FinFinancingItems> finFinancingItemsList = caseFinancingItemsService.list(Wrappers.<FinFinancingItems>query().lambda()
                    .eq(FinFinancingItems::getCarId, affix.getCarId())
                    .notIn(FinFinancingItems::getFinanceItemCode, FinanceItemEnum.CARAMT.getCode())
            );
            if (!CollectionUtils.isEmpty(finFinancingItemsList)) {
                affixInfo.setFinancingItems(finFinancingItemsList);
            }
            /**  设置总金额  **/
            approveCostPageInfoVo.setContAmt(ObjectUtils.isNotEmpty(approveCostPageInfoVo.getContAmt()) ? approveCostPageInfoVo.getContAmt().add(affix.getContractAmt()) : affix.getContractAmt());
            approveCostPageInfoVo.setLoanAmt(ObjectUtils.isNotEmpty(approveCostPageInfoVo.getLoanAmt()) ? approveCostPageInfoVo.getLoanAmt().add(affix.getLoanAmt()) : affix.getLoanAmt());
            approveCostPageInfoVo.setDownPayAmt(ObjectUtils.isNotEmpty(approveCostPageInfoVo.getDownPayAmt()) ? approveCostPageInfoVo.getDownPayAmt().add(affix.getDownPayAmt()) : affix.getDownPayAmt());
            approveCostPageInfoVo.setTailPayAmt(ObjectUtils.isNotEmpty(approveCostPageInfoVo.getTailPayAmt()) ? approveCostPageInfoVo.getTailPayAmt().add(affix.getTailPayAmt()) : affix.getTailPayAmt());
            approveCostPageInfoVo.setMonthPayAmt(ObjectUtils.isNotEmpty(approveCostPageInfoVo.getMonthPayAmt()) ? approveCostPageInfoVo.getMonthPayAmt().add(affix.getMonthPayAmt()) : affix.getMonthPayAmt());
            approveCostPageInfoVo.setInterestAmt(ObjectUtils.isNotEmpty(approveCostPageInfoVo.getInterestAmt()) ? approveCostPageInfoVo.getInterestAmt().add(affix.getTotalInterest()) : affix.getTotalInterest());

            /**  设置附加贷标记  **/
            approveCostPageInfoVo.setHasAffix(true);
        }

        approveCostPageInfoVo.setAffix(affixInfo);

        return approveCostPageInfoVo;
    }


    /**
     * copyOriginalInfo
     * <p>Description: 备份最原始融资信息</p>
     *
     * @param
     * @return
     */
    private void copyOriginalInfo(FinCostDetails carCost, FinCostDetails affifx) {
        if (ObjectUtils.isNotEmpty(carCost)) {
            CaseCostInfoOriginal carCostOriginal = caseCostInfoOriginalService.getById(carCost.getId());
            if (ObjectUtils.isEmpty(carCostOriginal)) {
                carCostOriginal = new CaseCostInfoOriginal();
                BeanUtils.copyProperties(carCost, carCostOriginal);
                caseCostInfoOriginalService.save(carCostOriginal);
            }
        }
        if (ObjectUtils.isNotEmpty(affifx)) {
            CaseCostInfoOriginal affifxOriginal = caseCostInfoOriginalService.getById(affifx.getId());
            if (ObjectUtils.isEmpty(affifxOriginal)) {
                affifxOriginal = new CaseCostInfoOriginal();
                BeanUtils.copyProperties(affifx, affifxOriginal);
                caseCostInfoOriginalService.save(affifxOriginal);
            }
        }
    }
    @Override
    public CaseCostInfoVO costTotal(String applyNo) {
        List<FinCostDetails> caseFinancingItemsList = this.list(Wrappers.<FinCostDetails>query().lambda()
                .eq(StringUtils.isNotEmpty(applyNo), FinCostDetails::getApplyNo, applyNo));
        CaseCostInfoVO costInfo = new CaseCostInfoVO();
        /** 合同金额 */
        BigDecimal contAmt = BigDecimal.ZERO;
        /** 首付金额 */
        BigDecimal downPayAmt = BigDecimal.ZERO;
        /** 尾付金额 */
        BigDecimal tailPayAmt = BigDecimal.ZERO;
        /** 贴息总额 */
        BigDecimal subsidyTotalAmt = BigDecimal.ZERO;
        /** 贷款金额 */
        BigDecimal loanAmt = BigDecimal.ZERO;
        /** 利息总额 */
        BigDecimal interestAmt = BigDecimal.ZERO;
        /** 月供金额 */
        BigDecimal monthPayAmt = BigDecimal.ZERO;

        String carProduct="";
        String discountProduct="";
        if (!CollectionUtils.isEmpty(caseFinancingItemsList)) {
            for (FinCostDetails caseCostInfo : caseFinancingItemsList) {
                contAmt = contAmt.add(null != caseCostInfo.getContractAmt() ? caseCostInfo.getContractAmt() : BigDecimal.ZERO);
                contAmt = contAmt.add(null != caseCostInfo.getAddAmt() ? caseCostInfo.getAddAmt(): BigDecimal.ZERO);
                downPayAmt = downPayAmt.add(null != caseCostInfo.getDownPayAmt() ? caseCostInfo.getDownPayAmt() : BigDecimal.ZERO);
                tailPayAmt = tailPayAmt.add(null != caseCostInfo.getTailPayAmt() ? caseCostInfo.getTailPayAmt() : BigDecimal.ZERO);
                subsidyTotalAmt = subsidyTotalAmt.add(null != caseCostInfo.getDiscountAmt() ? caseCostInfo.getDiscountAmt() : BigDecimal.ZERO);
                loanAmt = loanAmt.add(null != caseCostInfo.getLoanAmt() ? caseCostInfo.getLoanAmt() : BigDecimal.ZERO);
                interestAmt = interestAmt.add(null != caseCostInfo.getTotalInterest() ? caseCostInfo.getTotalInterest() : BigDecimal.ZERO);
                monthPayAmt = monthPayAmt.add(null != caseCostInfo.getMonthPayAmt() ? caseCostInfo.getMonthPayAmt() : BigDecimal.ZERO);

                if(caseCostInfo.getCostType().equals(CostTypeEnum.CARAMT.getCode())){
                    carProduct=caseCostInfo.getProductId();
                }
                if(caseCostInfo.getCostType().equals(CostTypeEnum.AFFIXAMT.getCode())){
                    discountProduct=caseCostInfo.getProductId();
                }
            }
            costInfo.setContAmt(contAmt);
            costInfo.setDownPayAmt(downPayAmt);
            costInfo.setTailPayAmt(tailPayAmt);
            costInfo.setSubsidyTotalAmt(subsidyTotalAmt);
            costInfo.setLoanAmt(loanAmt);
            costInfo.setInterestAmt(interestAmt);
            costInfo.setMonthPayAmt(monthPayAmt);
            boolean sameProduct=true;
            if(carProduct!=""&&discountProduct!=""&&!carProduct.equals(discountProduct)){
                sameProduct=false;
            }
            costInfo.setSameProduct(sameProduct);
            log.info("*****************end:查询费用总信息【" + applyNo + "】*****************");
            return costInfo;
        }
        return null;
    }

    @Override
    public void deleteByApplyNo(String applyNo) {
        baseMapper.deleteByApplyNo(applyNo);
    }

}
